var CLICKED_ITEM_NODE = {};// 收录已经装过(加载过)内容的节点的id
	var SUBMITLOCK = false;
	$(function() { 
		$("img").lazyload();
		loadFirstGoodsData();
		$("#cartMessageBox").click(submitCart);
		var menuItem = $("#types").find("ul > li");
		menuItem.each(function(index) {
			$(this).click(function() {
				menuItem.removeClass("active");
				$(this).addClass("active");
				var selectId = jQuery.trim($(this).attr("id"));
				changeGoodsItem(selectId);
			});
		});
		$("#next").click(checkAndDoNext);
	});
	
	function loadFirstGoodsData() {
		loadGoodsItem("MEAT_DIET","meatContentBox");
		CLICKED_ITEM_NODE["meatContentBox"] = "clicked";
	}

	function changeGoodsItem(selectId) {
		window.setTimeout(function(){
			var selectType = "MEAT_DIET";
			var contentBoxId = "meatContentBox";
			if (selectId == "vegetableItem") {
				selectType = "VEGETABLE";
				contentBoxId = "vegetableContentBox";
			}
			if (selectId == "soupItem") {
				selectType = "SOUP";
				contentBoxId = "soupContentBox";
			}
			if (selectId == "specialityItem") {
				selectType = "SPECIALITY";
				contentBoxId = "specialityContentBox";
			}
			$("#goodsContentBox").find(".goodsItemContentBox").css("display", "none");
			$("#"+contentBoxId).css("display", "block");
			if (CLICKED_ITEM_NODE[contentBoxId] && CLICKED_ITEM_NODE[contentBoxId] == "clicked") {
				
			} else {
				$("#"+contentBoxId).html($("#bigLoadingImg").html());
				loadGoodsItem(selectType, contentBoxId);
			}
		}, 50);
	}

	function loadGoodsItem(type,id){
		$.ajax({
			url: WEBROOT +'/goods/getGoods',
			data: {
				'goodsType' : type
			},
			type: 'post',
			async: false,
			dataType: 'json',
			headers: {
				"Content-Base" : jQuery.trim($("#base").html())
			},
			success: function(res) {
				if(res.result == 0){
					CLICKED_ITEM_NODE[id] = "clicked";
					var contentNode = $("#"+id);
					var goodsList = res.goodsList;
					var goodsListLength = goodsList.length;
					if (goodsListLength == 0) {
						contentNode.html("<div class=\"alert_message_box\">亲,抱歉,当前还没有该系列菜品推出, 如果您需要我们将尽快推出该系列菜品</div>");
					} else {
						contentNode.html("");
						createGoodsItemNodesToPage(goodsList, contentNode);
						$(".item-image").click(selectGoodsItem);
					}
				}
			}
		});
	}
	
	function createGoodsItemNodesToPage(goodsList, contentNode) {
		for(var i = 0; i < goodsList.length; i++){
			var goods = goodsList[i];

			var htmlStr = '<div class="item" id="'+goods.goodsId+'">'+
							'<div class="item-title">'+goods.goodsName+'</div>'+
							/* '<div class="item-image" onclick="selectGoodsItem(\''+goods.goodsId+'\', this)"><img src="'+WEBROOT+'/resource/images/androidOrder/lazyLoad.gif"  data-original="'+goods.goodsPicUrl+'" style="width: 100%;height: 110px;margin-top: 0px;" /></div>'+ */
							'<div class="item-image"><img src="'+WEBROOT+'/resource/images/androidOrder/lazyLoad.gif"  data-original="'+goods.goodsPicUrl+'" style="width: 100%;height: 110px;margin-top: 0px;" /></div>'+
							'<div class="single-item-info">'+
								'<div class="item-price"><span><img src="'+WEBROOT+'/resource/images/androidOrder/androidOrder2.png" style="width: 10px;height: 12px;" /></span><span>'+goods.goodsPrice+'</span></div>'+
								'<div class="item-amount"><span><img src="'+WEBROOT+'/resource/images/androidOrder/androidOrder3.png" style="width: 15px;height: 14px;" /></span><span>2人份</span></div>'+
								/* '<div class="item-detail"><a>详情</a> <img src="'+WEBROOT+'/resource/images/androidOrder/androidOrder.png" /></div>'+ */
							'</div>'+
							'<div class="select-shadow">'+
								'<div>'+
									'<img src="'+WEBROOT+'/resource/images/androidOrder/check.png"/>'+
									'<span>已选</span>'+
								'</div>'+
							'</div>'+
						'</div>';

			contentNode.append(htmlStr);
		}
	}
	
	function selectGoodsItem() {
		var $this = $(this);
		var selectItemNode = $this.parent('.item');
		$this.unbind('click');
		var shadowNode = selectItemNode.find(".select-shadow");
		var gId = jQuery.trim(selectItemNode.attr("id"));
		shadowNode.css({"display": "block"});
		// 添加这个商品到购物车
		doAddGoodsToCart(gId, selectItemNode, function(){
			shadowNode.click(function(){
				$(this).unbind('click');
				$(this).css({"display": "none"});
				// 从购物车移除这个商品
				doRemoveGoodsToCart(gId, selectItemNode, function(){$this.click(selectGoodsItem);});
			});
		});
	}
	
	function doAddGoodsToCart(gId, selectItemNode, callBackFunc) {
		if (gId != undefined && gId != null && "" != gId) {
			SUBMITLOCK = true;
			cartMessageShowWait();
			$.ajax({
				url: WEBROOT + '/cart/add',
				data: {
					'gd' : gId
				},
				type: 'post',
				dataType: 'json',
				headers: {
					"Content-Base" : jQuery.trim($("#base").html())
				},
				success: function(res) {
					if (res.result == 0) {
						callBackFunc();
						changeShowCartMessage(res.tg, res.tp);
					} else {
						selectItemNode.find(".select-shadow").css("display", "none");
						alert("服务器繁忙,请刷新重试");
					}
					cartMessageRemoveWait();
					SUBMITLOCK = false;
				}
			});
		}
	}
	
	function doRemoveGoodsToCart(gId, selectItemNode, callBackFunc) {
		if (gId != undefined && gId != null && "" != gId) {
			SUBMITLOCK = true;
			cartMessageShowWait();
			$.ajax({
				url: WEBROOT + '/cart/remove',
				data: {
					'gd' : gId
				},
				type: 'post',
				dataType: 'json',
				headers: {
					"Content-Base" : jQuery.trim($("#base").html())
				},
				success: function(res) {
					if (res.result == 0) {
						callBackFunc();
						changeShowCartMessage(res.tg, res.tp);
					} else {
						selectItemNode.find(".select-shadow").css("display", "block");
						alert(res.message + ",可能是手机浏览器不支持");
					}
					cartMessageRemoveWait();
					SUBMITLOCK = false;
				}
			});
		}
	}
	
	// 改变显示购物信息的绿色框框内的数据
	function changeShowCartMessage(goodsNum, totalPrice) {
		var cartMessageBox = $("#cartMessageBox");
		if (goodsNum == 0) {
			$("#before-submit").css("display", "block");
			cartMessageBox.css("display", "none");
		} else {
			$("#before-submit").css("display", "none");
			cartMessageBox.css("display", "block");
		}
		cartMessageBox.find("#cartMessageCount").html(goodsNum);
		cartMessageBox.find("#cartMessageAmount").html(Number(totalPrice).toFixed(2));
	}
	
	function submitCart() {
		if (Number($("#cartMessageCount").html()) > 0 && Number($("#cartMessageAmount").html()) > 0 && !SUBMITLOCK) {
			loadCartMessage();
			$("#goodsItems").css({"display": "none"});
			$("#order-container").css({"display": "block"});
			// 返回按钮的效果
			$("#back").click(function(){
				$("#goodsItems").css({"display": "block"});
				$("#order-container").css({"display": "none"});
			});
		} else
			alert("亲,请先选菜吧");
	}
	
	function initOrderContainer() {
		// 加载 "+", "-"号的事件效果
		$(".addGoodsNum").click(changeStyleAndAddGoodsNum);
		$(".delete-btn").click(showTheChangeAndRemoveGoodsFromCart);
		$(".minusGoodsNum").click(changeStyleAndReduceGoodsNum);
	}
	
	function changeStyleAndAddGoodsNum() {
		// 修改数目, 让减号显示出来,并绑定减号的点击事件, 考虑让价格样式处于改变状态
		// 提交数据, 成功后修改价格
		var $this = $(this);
		$this.unbind('click');
		$this.html($("#littleLoadingImg").html());
		var selectNode = $this.parent(".select-box");
		var goodsAmountNode = selectNode.find(".amount");
		var gi = jQuery.trim(selectNode.parent(".confirmation-item").find("._gi").val());
		if (gi && "" != gi) {
			$.ajax({
				url: WEBROOT + "/cart/addGoodsNum",
				type: "post",
				dataType: "json",
				data: {
					'gd': gi
				},
				headers: {
					"Content-Base" : jQuery.trim($("#base").html())
				},
				success: function(res) {
					if (res.result == 0) {
						var nowGoodsAmount = parseInt(jQuery.trim(goodsAmountNode.val()));
						goodsAmountNode.val(nowGoodsAmount + 1);
						changeShowTotlaPrice(res.tg, res.tp);
						if (nowGoodsAmount == 1) {
							selectNode.find(".minusGoodsNum").removeClass("disabled");
						}
						$this.bind({
							'click' : changeStyleAndAddGoodsNum
						});
						$this.html("+");
					} else {
						alert("系统繁忙请稍后重试");
					}
				}
			});
		}
	}
	
	function changeStyleAndReduceGoodsNum() {
		var $this = $(this);
		
		if (/(disabled){1}/.test(jQuery.trim($this.attr("class")))) {
			return ;
		}
		$this.unbind('click');
		$this.html($("#littleLoadingImg").html());
		var selectNode = $(this).parent(".select-box");
		var goodsAmountNode = selectNode.find(".amount");
		var gi = jQuery.trim(selectNode.parent(".confirmation-item").find("._gi").val());
		if (gi && "" != gi) {
			$.ajax({
				url: WEBROOT + "/cart/reduceGoodsNum",
				type: "post",
				dataType: "json",
				data: {
					'gd': gi
				},
				headers: {
					"Content-Base" : jQuery.trim($("#base").html())
				},
				success: function(res) {
					if (res.result == 0) {
						var nowGoodsAmount = parseInt(jQuery.trim(goodsAmountNode.val()));
						goodsAmountNode.val(nowGoodsAmount - 1);
						// 改变总价
						changeShowTotlaPrice(res.tg, res.tp);
						$this.click(changeStyleAndReduceGoodsNum);
						if (nowGoodsAmount <= 2) {
							$this.addClass("disabled");
						}
						$this.html("—");
					} else {
						alert("系统繁忙请稍后重试");
					}
				}
			});
		}
	}
	
	function changeShowTotlaPrice(goodsNum, totalPrice) {
		if (undefined == goodsNum || undefined == totalPrice)
			return ;
		$("#totalBox").html(Number(totalPrice).toFixed(2));
		changeShowCartMessage(goodsNum, totalPrice);
		if (goodsNum == 0) {
			$("#goodsItems").css({"display": "block"});
			$("#order-container").css({"display": "none"});
		}
	}
	
	function showTheChangeAndRemoveGoodsFromCart() {
		// 移除商品
		// 修改显示价格
		// 改变显示
		var deleteNode = $(this).parent(".delete").parent(".confirmation-item");
		var gi = jQuery.trim(deleteNode.find("._gi").val());
		if (gi && "" != gi) {
			deleteNode.css("display", "none");
			$.ajax({
				url: WEBROOT + "/cart/remove",
				type: "post",
				dataType: "json",
				data: {
					"gd": gi
				},
				headers: {
					"Content-Base" : jQuery.trim($("#base").html())
				},
				success: function(res) {
					if (res.result == 0) {
						deleteNode.remove();
						changeShowTotlaPrice(res.tg, res.tp);
						$("#"+gi).find(".select-shadow").css("display", "none");
						$("#"+gi).find(".item-image").click(selectGoodsItem);
					} else {
						deleteNode.css("display", "block");
						alert("抱歉,系统繁忙,请稍后重试");
					}
				}
			});
		}
	}
	
	function loadCartMessage() {
		$.ajax({
			url: WEBROOT + '/cart/shoppingCartMessage',
			type: 'post',
			dataType: 'json',
			headers: {
				"Content-Base" : jQuery.trim($("#base").html())
			},
			success: function(res) {
				if (res.result == 0) {
					createOrderNodeToPage(res);
				} else {
					alert("服务器异常");
				}
			}
		});
	}
	
	function createOrderNodeToPage(cartMessage) {
		$("#totalBox").html(Number(cartMessage.tp).toFixed(2));
		var itemsNode =  $("#item-list").find("ul");
		var htmlStr = '';
		itemsNode.html("");
		$.each(cartMessage.goodsList, function(index, goods) {
			var goodsNum = goods.goodsQuantity;
			var minusGoodsNumStr = goodsNum == 1 ? '<span class="minusGoodsNum disabled">—</span>' : '<span class="minusGoodsNum">—</span>';
			htmlStr =   '<li>'+
							'<div class="confirmation-item">'+
								'<div class="item-info">'+
									'<span class="item-name" title="'+goods.goodsName+'">'+goods.goodsName+'<br /></span>'+
									'<span class="item-price-info">'+
										'<span>'+
											'<span class="item-total-price">&yen;&nbsp;'+goods.goodsPrice+'</span>'+
										'</span>'+
									'</span>'+
								'</div>'+
								'<div class="select-box">'+
									minusGoodsNumStr+
									'<input class="amount" type="text" name="amount" value="'+goodsNum+'" autocomplete="off" readonly />'+
									'<span class="addGoodsNum">+</span>'+
								'</div>'+
								'<div class="delete">'+
									'<a class="delete-btn" href="javascript:void(0)"><img src="'+WEBROOT+'/resource/images/androidOrder/deleteGoods.png" /></a>'+
								'</div>'+
								'<div class="divider">'+
									'<input type="hidden" class="_gi" value="'+goods.goodsId+'">'+
								'</div>'+
							'</div>'+
						'</li>';
						
			itemsNode.append(htmlStr);
		});
		// 加载心增加数据的点击事件
		initOrderContainer();
	}
	
	function checkAndDoNext() {
		if (Number(jQuery.trim($("#totalBox").html())) > 0) {
			showBuyerMessageBox();
			initBuyerPage();
		}
	}
	
	function showBuyerMessageBox() {
		$("#order-container").css("display", "none");
		$("#buyer-container").css("display", "block");
	}
	
	function initBuyerPage() {
		$("#buyerBack").click(function(){
			$("#order-container").css("display", "block");
			$("#buyer-container").css("display", "none");
		});
		$("#submitOrder").click(checkAndSubmitOrder);
		$("#note").blur(function() {
			var node = $("#note");
			if (jQuery.trim(node.val()).length > 0) {
				node.val(changeScript(node.val()));
			} else {
				node.val(null);
			}
		});
	}
	
	function checkAndSubmitOrder() {
		var formNode = $("#buyerMessageForm");
		var userName = jQuery.trim(formNode.find("#username").val());
		var phoneNum = jQuery.trim(formNode.find("#tel").val());
		var addr = jQuery.trim(formNode.find("#addr").val());
		var date = formNode.find("input[name=\"orderReceiveDt\"]:checked").val();
		if (!isEmpty(userName) && isPhoneNum(phoneNum) && !isEmpty(addr) && isDate(date)) {
			$(this).parent(".toolbar").html('<div class="mybtn" style="background: #E4E4E4;">' +$("#littleLoadingImg").html()+ '</div>');
			$.ajax({
				url: WEBROOT+"/orderForm/generateOrder",
				type: "post",
				dataType: "json",
				data: {
					"buyerName": userName,
					"buyerPhoneNumber": phoneNum,
					"buyerAddr": addr,
					"orderReceiveDt": date,
					"remark": jQuery.trim($("#note").html())
				},
				headers: {
					"Content-Base" : jQuery.trim($("#base").html())
				},
				success: function(res) {
					if (res.result == 0) {
						/* alert("订单号为:" + res.on); */
						var orderMessageNode = $("#orderMessage");
						orderMessageNode.find("#orderNo").html(res.on);
						$("#content").html(orderMessageNode.html());
					} else {
						alert("交易过程中出现错误, 请重试");
					}
				}
			});
		} else {
			alert("亲,为了保障您及时收到新鲜菜品,请先完善信息");
		}
	}
	
	function isPhoneNum(str) {
		var regex = /^[0-9\ \-]{5,}$/;
		if (regex.test(str))
			return true;
		return false;
	}
	
	function isEmpty(obj) {
		if (obj == null || obj == undefined || jQuery.trim(obj).length == 0 || obj == "" || obj === "null") {
			return true;
		}
		return false;
	}
	
	function isDate(str) {
		if (str == "today" || str == "tomorrow")
			return true;
		return false;
	}
	
	function changeScript(str) {
		str = jQuery.trim(str);
		var reg = new RegExp("<.*?script[^>]*?>.*?(<\/.*?script.*?>)*","ig");
		return str.replace(reg, "");
	}
	
	function cartMessageShowWait() {
		$("#before-submit").css("display", "none");
		$("#cartMessageBox").css("display", "none");
		$("#cartMessageBox").parent(".toolbar").append('<div id="waitBox" class="mybtn" style="background: #E4E4E4;">' +$("#littleLoadingImg").html()+ '</div>');
	}
	
	function cartMessageRemoveWait() {
		$("#waitBox").remove();
		$("#cartMessageBox").css("display", "block");
	}